﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using BLinq;
using System.Net;
using System.Windows.Threading;
using ManagedWinapi;
using Image = System.Windows.Controls.Image;
using MessageBox = System.Windows.MessageBox;
using System.Windows.Media.Animation;

namespace BingIt
{
    public partial class BingItWindow : Window
    {
        private BingContext _bing;
        private IQueryable<PageSearchResult> _pages;
        private ManagedWinapi.Hotkey _hotKey = new ManagedWinapi.Hotkey();
        private NotifyIcon _mynotify;

        public BingItWindow()
        {
            ShowSplashScreen();
            InitializeComponent();

            _bing = new BingContext("EE8ADBE91A159F5C11005625A6DFB69BA83037FA");
            
            _hotKey.Ctrl = true;
            _hotKey.Shift = true;
            _hotKey.KeyCode = Keys.B;
            _hotKey.Enabled = true;
            _hotKey.HotkeyPressed += new EventHandler(hotKey_HotkeyPressed);

            _mynotify = new NotifyIcon();
            _mynotify.Click += notifyIcon_Click;
            Icon myicon = new Icon("./search_icon.ICO");
            _mynotify.Icon = myicon;
            _mynotify.Visible = true;
            _mynotify.BalloonTipTitle = "BingIt";
            _mynotify.BalloonTipText = "Restore BingIt";

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            searchTextBox.Text = String.Empty;
            searchTextBox.Focus();
        }

        private void GetPages()
        {
            pagesListBox.Items.Clear();
            _pages = from p in _bing.Pages
                     where p.Query == searchTextBox.Text.ToString()
                     select p;
            _pages = _pages.Take(Int32.Parse(firstResultsTextBox.Text.ToString()));

            foreach (var page in _pages)
            {
                TextBlock textBlock = new TextBlock();
                Run run = new Run(page.Title);
                Hyperlink link = new Hyperlink(run);
                link.NavigateUri = page.Uri;
                link.Click += new RoutedEventHandler(link_Click);
                textBlock.Inlines.Add(link);
                textBlock.Inlines.Add("\n" + page.Description);
                pagesListBox.Items.Add(textBlock);
            }
        }

        private void GetImages()
        {
            var images = from i in _bing.Images
                         where i.Query == searchTextBox.Text.ToString()
                         select i;
            images = images.Take(Int32.Parse(firstResultsTextBox.Text.ToString()));

            imagesListBox.Items.Clear();
            foreach (var result in images)
            {
                Image myImage = new Image();
                myImage.Width = result.ThumbnailWidth;
                myImage.Height = result.ThumbnailHeight;
                BitmapImage myBitmapImage = new BitmapImage();
                myBitmapImage.BeginInit();
                myBitmapImage.UriSource = result.MediaUri;
                myBitmapImage.DecodePixelWidth = result.ThumbnailWidth;
                myBitmapImage.EndInit();
                myImage.Source = myBitmapImage;

                TextBlock block = new TextBlock();
                block.Inlines.Add(myImage);

                Run run = new Run(result.Title);
                Hyperlink link = new Hyperlink(run);
                link.NavigateUri = result.Uri;
                link.Click += new RoutedEventHandler(link_Click);
                block.Inlines.Add(link);
                block.Inlines.Add("\n");

                Run run1 = new Run("Show Image");
                Hyperlink link1 = new Hyperlink(run1);
                link1.NavigateUri = result.MediaUri;
                link1.Click += new RoutedEventHandler(link_Click);
                block.Inlines.Add(link1);
                block.Inlines.Add("\n");

                Run run2 = new Run("Download Image");
                Hyperlink link2 = new Hyperlink(run2);
                link2.NavigateUri = result.MediaUri;
                link2.Click += new RoutedEventHandler(download_Click);
                block.Inlines.Add(link2);
                block.Inlines.Add("\n");

                imagesListBox.Items.Add(block);
            }

        }

        private void ShowSplashScreen()
        {
            SplashScreen splashScreen = new SplashScreen("splash_image.bmp");
            splashScreen.Show(true);
        }

        void hotKey_HotkeyPressed(object sender, EventArgs e)
        {
            this.WindowState = WindowState.Normal;
            searchTextBox.Focus();
        }

        private void searchTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.Cursor = System.Windows.Input.Cursors.Wait;
                searchButton_Click(this, new RoutedEventArgs());
                this.Cursor = System.Windows.Input.Cursors.Arrow;
            }
        }
     
        private void ShowNotifyIcon(object sender, EventArgs e)
        {
            if(WindowState == System.Windows.WindowState.Minimized)
            {
                _mynotify.ShowBalloonTip(1000);
                this.ShowInTaskbar = false;
            }
        }

        private void searchButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = System.Windows.Input.Cursors.Wait;
                GetPages();
                if (imagesCheckBox.IsChecked == true)
                    GetImages();
                this.Cursor = System.Windows.Input.Cursors.Arrow;

            }
            catch (Exception caught)
            {
                MessageBox.Show(caught.Message);
            }
        }

        private void download_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink hyperLink = (Hyperlink)sender;

            WebRequest requestPic = WebRequest.Create(hyperLink.NavigateUri.ToString());
            WebResponse responsePic = requestPic.GetResponse();

            System.Drawing.Image webImage = System.Drawing.Image.FromStream(responsePic.GetResponseStream());

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.ShowDialog();

            char[] separator = { '.' };
            string[] strings = new string[15];
            strings = hyperLink.NavigateUri.ToString().Split(separator, 15);
            ;

            webImage.Save(saveFileDialog.FileName + "." + strings[strings.Count() - 1]);
        }

        private void link_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink hyperlink = (Hyperlink)sender;
            System.Diagnostics.Process.Start(hyperlink.NavigateUri.ToString());
        }
    
        void notifyIcon_Click(object sender, EventArgs e)
        {
            this.WindowState = WindowState.Normal;
            this.ShowInTaskbar = true;
            searchTextBox.Focus();
        }

        private void expander1_Expanded(object sender, System.Windows.RoutedEventArgs e)
        {
            DoubleAnimation da = new DoubleAnimation(0.0, 125.0, new Duration(new TimeSpan(0, 0, 1)));
            expander1.BeginAnimation(Expander.HeightProperty, da);
        }
    }

}